<?php
/**
 * 微信消息模型
 * */
namespace Mob \ Model;

use Think \ Model;
use Think \ Hook;
require_once('./Application/Mob/Common/function.php');
class WxMessageModel extends Model
{

	public function getTemplate($type)
	{

     $temp= cache_get('Wxtemplate_'.$type);
    if($temp)
    {
    return 	$temp;
    }
	 $template = M('template');
	 $where = array('type'=>$type,'status'=>1);
	$res = $template->where($where)->field('template_data,template_name,template_id,template_type')->find();
    cache_set('Wxtemplate_'.$type,$res);
    return $res;
	}

  public function MessageRecord($srcUid='1',$receiveUid,$receiveOpenId,$sendcontent,$templateId,$type,$res)
  {
   $mesage = M('wx_message');
   $data['senduid']=$srcUid;
   $data['receiveuid']=$receiveUid;
   $data['receiveopenid']=$receiveOpenId;
   $data['sendcontent']=$sendcontent;
   $data['templateId']=$templateId;
   $data['errcode']=$res['errcode'];
   $data['errmsg']=$res['errmsg'];
   $data['msgid']=$res['msgid'];
   $mesage->add($data);

  }
  public function sendMessage($SrcUid,$receiveUid,$type,$data)
  {

  $openid = D('WxUser')->queryWxUserOpenId($receiveUid);

  $template= $this->getTemplate($type);


  if(empty($openid)||empty($template))
  {
  return false;
  }
  $templateId = $template['template_id'];


  $res = $this->doSend($openid,$templateId,$data);
  $res = json_decode($res,true);
  $this->MessageRecord($SrcUid,$receiveUid,$openid,serialize($data),$templateId,$type,$res);
  if($res['errcode']==0)
  {
  return true;
  }else
  {
  return false;
  }

  }



   /**
     * 发送自定义的模板消息
     * @param $touser
     * @param $template_id
     * @param $url
     * @param $data
     * @param string $topcolor
     * @return bool
     */
    public function doSend($touser, $template_id,$data, $topcolor = '#7B68EE')
    {

        /*
         * data=>array(
                'first'=>array('value'=>urlencode("您好,您已购买成功"),'color'=>"#743A3A"),
                'name'=>array('value'=>urlencode("商品信息:微时代电影票"),'color'=>'#EEEEEE'),
                'remark'=>array('value'=>urlencode('永久有效!密码为:1231313'),'color'=>'#FFFFFF'),
            )
         */
        $template = array(
            'touser' => $touser,
            'template_id' => $template_id,
            'url' => $url,
            'topcolor' => $topcolor,
            'data' => $data
        );
        $json_template = json_encode($template);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . D('WxCommon')->accessToken;
        $dataRes = D('WxCommon')->request_post($url, urldecode($json_template));
        return $dataRes;
        /*
        if ($dataRes['errcode'] == 0) {
            return true;
        } else {
            return false;
        }
        */
    }



















}